import NavBarAgain from "./../../components/NavBarAgain";
import { queryUserStoreList, storeRemove } from "./../../service/api";
import { useEffect, useState } from "react";
import { Skeleton, List, SwipeAction, Toast } from "antd-mobile";
import { Action, SwipeActionRef } from "antd-mobile/es/components/swipe-action";
import "./index.less";
const Collect = (props) => {
  const { navigate } = props;
  let [collectData, setCollectData] = useState(null);

  /* 获取收藏列表 */
  const getCollect = async () => {
    try {
      const { code, data } = await queryUserStoreList();
      if (code === 0) {
        setCollectData(data);
      } else {
        console.log("获取登录者收藏列表失败", error);
      }
    } catch (error) {
      console.log("获取登录者收藏列表失败", error);
    }
  };

  /* 跳转到详情页面 */
  const handleJump = (newsId) => {
    navigate(`/details/${newsId}`);
  };

  /* 取消收藏 */
  const cancelCollect = async (id) => {
    try {
      let { code } = await storeRemove(id);
      if (code === 0) {
        Toast.show({
          icon: "success",
          content: "取消收藏成功",
        });
        getCollect();
        return;
      } else {
        Toast.show({
          icon: "fail",
          content: "取消收藏失败",
        });
      }
    } catch (error) {
      console.log("移除收藏失败 ...", err);
    }
  };

  /* 组件第一次渲染完毕，获取数据 */
  useEffect(() => {
    getCollect();
  }, []);

  return (
    <div className="store-page">
      <NavBarAgain title="我的收藏" />
      <div className="content">
        {!collectData ? (
          <div>
            {" "}
            <Skeleton.Title animated /> <Skeleton.Paragraph animated />
          </div>
        ) : (
          collectData.map((item) => {
            const id = item.id;
            return (
              <SwipeAction
                key={item.news.id}
                onAction={cancelCollect.bind(null, id)}
                rightActions={[
                  {
                    key: item.news.id,
                    text: "取消收藏",
                    color: "warning",
                  },
                ]}
              >
                <div
                  className="store-item"
                  onClick={handleJump.bind(null, item.news.id)}
                >
                  <p>{item?.news?.title}</p>
                  <div>
                    <img src={item?.news?.image} alt="" />
                  </div>
                </div>
              </SwipeAction>
            );
          })
        )}
      </div>
      {collectData && collectData.length >= 0 ? (
        <p className="content-text">没有更多内容了</p>
      ) : null}
    </div>
  );
};

export default Collect;
